<template>
	<view>

		<!-- #ifdef APP-PLUS || MP-WEIXIN -->
		<u-navbar title="选择地址" back-icon-color="#000" :is-back="true" title-color="#000" :background="{ background:'#ffffff'}" :border-bottom="true">
			<!--
			<view class="address" @click="newadd()">新增地址</view>
			-->
		</u-navbar>
		<!-- #endif -->

		<view class="sousuo">
			<u-search placeholder="请输入地址" v-model="keyword" :show-action="false" @focus="focusju" @blur="shiqufocus" @change="changeSearch"></u-search>
		</view>

		<!--搜素结果列表-->
		<view class="search_res_wrap" v-if="searchMask">
			<view class="mask_box" @click="mask_click()"></view>
			<view class="search_res" v-if="searchList.length != 0">
				<view class="search_list" v-for="(item,index) in searchList" :key="index" @click="selectsearch(item)">
					<view class="search_item">
						<view class="sa_name">
							<rich-text :nodes="item.title"></rich-text>
						</view>
						<!--<view>{{(item._distance / 2 / 500).toFixed(2) + 'km'}}</view>-->
					</view>
					<view class="search_adres">{{item.address}}</view>
				</view>
			</view>
		</view>

		<!--默认列表-->
		<view class="content_box" v-else>
<!--   重新定位列表   -->
			<view class="current_address">
				<view class="c_name"><u-loading class="jiazaixxx" size="30" :show="skeletonLoading" color="#FFB930"></u-loading> <span @click="isxuanze()">{{addresCurrent}}</span></view>
				
				<!-- #ifdef APP-PLUS || MP-WEIXIN -->
				<view class="c_rbtn" @click="getloclat()"><u-icon name="map-fill" color="#FF611E" size="28"></u-icon>重新定位</view>
				<!-- #endif -->
				
				<!-- #ifdef H5 -->
				<view class="c_rbtn" @click="h5getloclat('anew')"><u-icon name="map-fill" color="#FF611E" size="28"></u-icon>重新定位</view>
				<!-- #endif -->
				
			</view>
			<u-gap height="40" bg-color="#F8F8F8" v-if="is_test == 1"></u-gap>
<!--测试员地址 测试用-->
      <view class="my_address_Box" v-if="is_test == 1">
				<view class="my_title">
					<u-icon name="car" color="#999999" size="32"></u-icon>
					<view>测试员地址</view>
					<view class="newadddizhi" @click="newadd()">新增地址</view>
				</view>
				<view class="address_list" v-if="addresList.length != 0">
					<view class="list_item" v-for="(item,index) in addresList" :key="index">
						<view class="a_name" @click="fanhuiHome(item)">
							<view class="dizhi">
								<span class="moren" v-if="item.is_default == 1">默认</span>
								<view class="tueAddres">{{item.address}} {{item.house_number}}</view>
							</view>
							<view class="u_name">
								<text>{{item.name}} {{item.sex}}</text>
								<text>{{item.tel}}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
			<u-gap height="40" bg-color="#F8F8F8"></u-gap>
<!--  附近的地址  -->
      <view class="my_address_Box">
				<view class="my_title2">
					<u-icon name="map" color="#999999" size="32"></u-icon>
					<view>附近的地址</view>
				</view>
				<view class="lanjiazai" v-if="skeletonLoading">
					<view>
						<u-loading :show="skeletonLoading" color="#FFB930"></u-loading>
						<view class="tag" style="font-size: 24rpx;">加载中...</view>
					</view>
				</view>
				<view class="address_list" v-else-if="poisList.length != 0">
					<view class="list_item" v-for="(items,indexs) in poisList" :key="indexs">
						<view class="a_name" @click="poisfanhuiHome(items)">
							<view class="dizhi">
								<view class="tueAddres">{{items.title}}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>


	</view>
</template>

<script>
	const app = getApp();
	export default {
		data() {
			return {
				BestImgUrl: app.globalData.imgurlBwc,
				addresCurrent: '定位中...',

				keyword: '',
				searchMask: false,
				searchList: [],
				addresList: [],
				poisList: [],

				skeletonLoading: true,
				
				CurrentAddressData: {},//点击重新定位后的当前位置信息
				is_test: 0
			}
		},
		onLoad() {
			//先获取经纬度
			// #ifdef APP-PLUS
			this.getloclat()
			// #endif
			
			// #ifdef H5
			this.h5getloclat('enterinto')
			// #endif
			
			// #ifdef MP-WEIXIN
			this.h5getloclat('enterinto')
			// #endif
			
			let token = uni.getStorageSync('token')
			if (!token) {
				this.is_test = 0
			} else {
				this.GetUserInfo()
			}
			
		},
		onShow() {
			//获取我的收货地址
			this.getaddlist()
		},
		methods: {
      // 获取个人用户信息
			GetUserInfo() {
				let that = this
				that.$api.GetuserInfo({
			
				}).then(res => {
					console.log('个人信息', res.data.result);
					that.is_test = res.data.result.is_test || 0;
				}).catch(err => {
					
				});
			},
      // 重新定位的app和weixin获取地址
			getloclat() {
				let that = this
				that.skeletonLoading = true
				that.addresCurrent = '定位中...'
				uni.getLocation({
					type: 'gcj02',
					//安卓H5打包开启 IOS打包注释掉  因为IOS上获取很慢位置问题
					//highAccuracyExpireTime: "3000",
					//isHighAccuracy: true,

					success: function(res) {
						console.log('获取经纬度', res)
						
						// let wdu = '24.890854'
						// let jdu = '102.82961'
						let wdu = res.latitude
						let jdu = res.longitude
						
						
						that.jiexi(wdu, jdu)
					},
					fail: function(err) {
						alert(JSON.stringify(err))
					}
				});
			},
      // 重新定位的h5获取地址
			h5getloclat(type) {
				let that = this
				that.skeletonLoading = true
				that.addresCurrent = '定位中...'
				
				let weidu = uni.getStorageSync('lat')
				let jingdu = uni.getStorageSync('lng')
				
				if(!weidu || !jingdu || type == 'anew'){
					console.log('本地没有经纬度')
					uni.getLocation({
						type: 'gcj02',
						highAccuracyExpireTime: "3000",
						isHighAccuracy: true,
						success: function(res) {
							console.log('获取经纬度', res)
							
							// let wdu = '24.890854'
							// let jdu = '102.82961'
							let wdu = res.latitude
							let jdu = res.longitude
							
							that.jiexi(wdu, jdu)
						},
						fail: function(err) {
							alert(JSON.stringify(err))
						}
					});
				}else {
					//本地有经纬度
					that.jiexi(weidu, jingdu)
				}
			},
			//然后解析这个经纬度
			jiexi(wdu, jdu) {
				let that = this

				// #ifdef H5
				this.$jsonp('https://apis.map.qq.com/ws/geocoder/v1/', {
					location: wdu + ',' + jdu,
					key: '7DZBZ-Q5BWK-23ZJ7-AOV3F-4VZBZ-NCFO3',
					get_poi: 1,
					poi_options: 'address_format=short;radius=5000;policy=2',
					output: 'jsonp'
				}).then(Nres => {
					console.log('H5-端当前城市信息', Nres)

					if (Nres.status === 0) {
						that.CurrentAddressData = Nres.result
						that.addresCurrent = Nres.result.address_component.street
						that.poisList = Nres.result.pois
						that.skeletonLoading = false
					} else {
						that.skeletonLoading = false
						that.poisList = []
					}

				}).catch(err => {
					that.skeletonLoading = false
					//console.log('H5-端当前城市信息', err)
				})
				// #endif

				// #ifdef APP-PLUS || MP
				uni.request({
					url: 'https://apis.map.qq.com/ws/geocoder/v1/',
					method: 'GET',
					data: {
						location: wdu + ',' + jdu,
						key: 'IOVBZ-V6GWL-VUZP4-MC4UF-TQIBO-ERFB7',
						get_poi: 1,
						poi_options: 'address_format=short;radius=5000;policy=2'
					},
					success(Nres) {
						console.log('解析数据', Nres)
						if (Nres.data.status === 0) {
							that.CurrentAddressData = Nres.data.result
							that.addresCurrent = Nres.data.result.address_component.street
							that.poisList = Nres.data.result.pois
							that.skeletonLoading = false
						} else {
							uni.showToast({
								title: '定位' + Nres.data.errMsg,
								icon: 'none',
								duration: 2000
							})
						}
					}
				})
				// #endif
			},
      // 测试员-获取我的收货地址
			getaddlist() {
				let that = this
				that.$api.shAddresslist({
					page: 1, //	否	int	页码 默认第一页
					limit: 20, //	否	int	每页条数 默认10条
				}).then(res => {
					that.addresList = res.data.result
				}).catch(err => {
					uni.showToast({
						title: err.data.msg,
						icon: 'none',
						duration: 2000
					});
				})
			},
      // 测试员选择地址并返回首页
			fanhuiHome(data) {
				console.log(data)
				uni.setStorageSync('lat', data.latitude);
				uni.setStorageSync('lng', data.longitude);
				uni.setStorageSync('address', data.address);
				
				uni.setStorageSync('CityName', data.city)
				uni.setStorageSync('Province', data.province)
				
				uni.$emit('Getlist', {
					id: 1,
				});
				uni.navigateBack()
			},
      // 选择重新定位的位置并返回首页
			isxuanze(){
				let data = this.CurrentAddressData
				console.log('选择重新定位的位置',data)
				uni.setStorageSync('lat', data.location.lat);
				uni.setStorageSync('lng', data.location.lng);
				uni.setStorageSync('address', data.formatted_addresses.recommend);
				
				uni.setStorageSync('CityName', data.ad_info.city)
				uni.setStorageSync('Province', data.ad_info.province)
				
				uni.removeStorageSync('meituan_session_id');
				uni.removeStorageSync('meituanPvId');
				
				uni.$emit('Getlist', {
					id: 1,
				});
				uni.navigateBack()
				
			},
      // 附近地址选择并返回首页
			poisfanhuiHome(data) {
				console.log('选择',data)
				uni.setStorageSync('lat', data.location.lat);
				uni.setStorageSync('lng', data.location.lng);
				uni.setStorageSync('address', data.title);
				
				uni.setStorageSync('CityName', data.ad_info.city)
				uni.setStorageSync('Province', data.ad_info.province)
				
				uni.removeStorageSync('meituan_session_id');
				uni.removeStorageSync('meituanPvId');
				
				uni.$emit('Getlist', {
					id: 1,
				});
				uni.navigateBack()
			},
			// 测试员新增地址
      newadd() {
				uni.navigateTo({
					url: '/addressPages/pages/myAddress/newAddress',
					animationType: 'pop-in'
				})
			},










































			//输入聚焦
			focusju() {
				//console.log('聚焦了')
				this.searchMask = true
			},
			//失去聚焦
			shiqufocus() {
				//console.log('失去聚焦了')
				//this.searchMask = false
			},
			//搜索输入
			changeSearch(key) {
				console.log(key)
				this.SearchRes(key)
			},
			//点击遮罩层
			mask_click() {
				this.searchMask = false
			},
			//开始执行搜索结果
			SearchRes(key) {
				let that = this
				let lat = uni.getStorageSync('lat');
				let log = uni.getStorageSync('lng');

				// #ifdef H5
				this.$jsonp('https://apis.map.qq.com/ws/place/v1/suggestion', {
					//orderby: '_distance',
					//filter: 'category=公司企业,娱乐休闲,房产小区,酒店宾馆', //筛选条件
					//get_subpois: 1, //是否返回子地点，如大厦停车场、出入口等取值
					//boundary: 'nearby(' + lat + ',' + log + ',1000)',
					page_size: 20,
					page_index: 1,
					keyword: key,
					key: '7DZBZ-Q5BWK-23ZJ7-AOV3F-4VZBZ-NCFO3',
					region: uni.getStorageSync("CityName"),
					region_fix: 1,
					location: lat + ',' + log,
					output: 'jsonp'
				}).then(Nres => {
					console.log('H5-搜索数据', Nres)
				
					if (Nres.status === 0) {
						//that.searchList = Nres.data
						
						if(Nres.data.length === 0){
							uni.showToast({
								title: '暂无数据',
								icon: 'none',
								duration: 2000
							})
						}else {
							let filterArr = [];
							// 过滤出符合条件的值
							Nres.data.forEach((item, index) => {
								filterArr.push({
									ad_info: {
										adcode: item.adcode,
										city: item.city,
										district: item.district,
										province: item.province,
									},
									address: item.address,
									category: item.category,
									id: item.id,
									location: {
										lat: item.location.lat,
										lng: item.location.lng
									},
									//tel: item.tel,
									title: that.join(item.title, key),
									lstTitle: item.title,
									type: item.type,
									//_distance: item._distance
								});
							});
							
							that.searchList = filterArr
							//console.log(that.searchList)
						}
						
					} else {
						that.searchList = []
					}
				
				}).catch(err => {
					
				})
				// #endif

				// #ifdef APP-PLUS || MP
				uni.request({
					url: 'https://apis.map.qq.com/ws/place/v1/suggestion',
					method: 'GET',
					data: {
						//orderby: '_distance',
						//filter: 'category=公司企业,娱乐休闲,房产小区,酒店宾馆', //筛选条件
						//get_subpois: 1, //是否返回子地点，如大厦停车场、出入口等取值
						//boundary: 'nearby(' + lat + ',' + log + ',1000)',
						page_size: 20,
						page_index: 1,
						keyword: key,
						key: '7DZBZ-Q5BWK-23ZJ7-AOV3F-4VZBZ-NCFO3',
						region: uni.getStorageSync("CityName"),
						region_fix: 1,
						location: lat + ',' + log
					},
					success(Nres) {
						console.log('搜索数据', Nres)
						if (Nres.data.status === 0) {
							//that.searchList = Nres.data.data
							if(Nres.data.data.length === 0){
								uni.showToast({
									title: '暂无数据',
									icon: 'none',
									duration: 2000
								})
							}else {
								let filterArr = [];
								// 过滤出符合条件的值
								Nres.data.data.forEach((item, index) => {
									filterArr.push({
										ad_info: {
											adcode: item.adcode,
											city: item.city,
											district: item.district,
											province: item.province,
										},
										address: item.address,
										category: item.category,
										id: item.id,
										location: {
											lat: item.location.lat,
											lng: item.location.lng
										},
										//tel: item.tel,
										title: that.join(item.title, key),
										lstTitle: item.title,
										type: item.type,
										//_distance: item._distance
									});
								});
								
								that.searchList = filterArr
								//console.log(that.searchList)
							}

						} else {
							that.searchList = []
							
						}
					}
				})
				// #endif
			},
			//高亮关键词
			join(str, key) {
				var reg = new RegExp((`(${key})`), "gm");
				var replace = '<span style="color:#FF611E;font-weight:bold;">$1</span>';
				return str.replace(reg, replace);
			},
			//选择搜索结果并返回首页
			selectsearch(data) {
				console.log('搜索选择',data)
				uni.setStorageSync('lat', data.location.lat);
				uni.setStorageSync('lng', data.location.lng);
				uni.setStorageSync('address', data.lstTitle);
				
				uni.setStorageSync('CityName', data.ad_info.city)
				uni.setStorageSync('Province', data.ad_info.province)
				
				uni.$emit('Getlist', {
					id: 1,
				});
				uni.navigateBack()
			}
		}
	}
</script>

<style lang="scss">
	.address {
		margin-left: auto;
		padding-right: 30rpx;
		color: #333333;
		font-size: 32rpx;
	}

	.search_res_wrap {
		position: relative;

		.mask_box {
			width: 100%;
			height: 100%;
			background-color: rgba(0, 0, 0, 0.45);
			position: fixed;
			z-index: 4;
		}

		.search_res {
			/* #ifdef MP-WEIXIN */
			padding: 0 30rpx 30rpx 30rpx;
			/* #endif */

			/* #ifdef H5 */
			padding: 120rpx 30rpx 30rpx 30rpx;
			/* #endif */

			/* #ifdef APP-PLUS */
			padding: 0 30rpx 30rpx 30rpx;
			/* #endif */


			position: relative;
			z-index: 6;
			background-color: #ffffff;

			.search_list {
				border-bottom: 1px solid #f3f3f3;
				padding: 20rpx 0 20rpx 0;

				.search_item {
					display: flex;
					align-items: center;
					justify-content: space-between;

					.sa_name {
						flex: 1;
					}

					view:nth-child(2) {
						color: #999;
						font-size: 24rpx;
					}
				}

				.search_adres {
					margin-top: 10rpx;
					color: #999;
					font-size: 24rpx;
					word-break: break-all;
					display: -webkit-box;
					-webkit-line-clamp: 1;
					-webkit-box-orient: vertical;
					overflow: hidden;
				}
			}
		}
	}

	.sousuo {
		padding: 30rpx;
		top: 0;
		width: 100%;

		/* #ifdef MP-WEIXIN */
		margin-top: 0;
		/* #endif */

		/* #ifdef H5 */
		margin-top: 0;
		position: fixed;
		/* #endif */

		/* #ifdef APP-PLUS */
		margin-top: 0;
		/* #endif */
		background-color: #ffffff;
		z-index: 7;
	}


	.content_box {


		/* #ifdef MP-WEIXIN */
		padding-top: 0;
		/* #endif */

		/* #ifdef H5 */
		padding-top: 116rpx;
		/* #endif */

		/* #ifdef APP-PLUS */
		padding-top: 0;
		/* #endif */

		.current_address {
			padding: 10rpx 30rpx 30rpx 30rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.c_name {
				flex: 1;
				word-break: break-all;
				display: -webkit-box;
				-webkit-line-clamp: 1;
				-webkit-box-orient: vertical;
				overflow: hidden;
				padding-right: 30rpx;

				.jiazaixxx {
					margin-right: 10rpx;
					position: relative;
					top: -3rpx;
				}
			}

			.c_rbtn {
				color: #FF611E;
				font-size: 28rpx;
			}
		}

		.my_address_Box {
			padding: 30rpx 30rpx 0 30rpx;

			.my_title {
				margin-bottom: 30rpx;
				display: flex;
				align-items: center;
				color: #999;

				.newadddizhi {
					margin-left: auto;
					color: #FF611E;
				}

				.u-icon {
					margin-right: 10rpx;
				}
			}

			.my_title2 {
				margin-bottom: 30rpx;
				display: flex;
				align-items: center;
				color: #999;

				.u-icon {
					margin-right: 10rpx;
				}
			}

			.address_list {

				.list_item {
					display: flex;
					align-items: center;
					padding: 26rpx 0;
					border-bottom: 1px solid #f3f3f3;

					.a_name {
						flex: 1;

						.dizhi {
							font-size: 28rpx;
							color: #333;
							display: flex;
							align-items: center;

							.moren {
								font-size: 24rpx;
								background-color: #05b6fd;
								color: #ffffff;
								border-radius: 10rpx;
								padding: 2rpx 10rpx;
								margin-right: 6rpx;
							}

							.tueAddres {
								word-break: break-all;
								display: -webkit-box;
								-webkit-line-clamp: 1;
								-webkit-box-orient: vertical;
								overflow: hidden;
							}
						}

						.u_name {
							font-size: 24rpx;
							color: #999;

							text:nth-child(1) {}

							text:nth-child(2) {
								padding-left: 30rpx;
							}
						}
					}

					.a_edit {
						margin-left: auto;
					}
				}
			}
		}
	}
</style>